package com.jnu.book;

import android.app.Application;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.model.LatLng;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MapFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MapFragment extends Fragment {


    public static final int WHAT_DATA_OK=1000;
    private MapView mapView;
    BitmapDescriptor bitmap= BitmapDescriptorFactory.fromResource(R.drawable.locator);

    public MapFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     *
     * @return A new instance of fragment MapFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MapFragment newInstance() {
        MapFragment fragment = new MapFragment();
        Bundle args = new Bundle();

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {

        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_map, container, false);
        mapView = view.findViewById(R.id.bmapView);

        LatLng centerPoint =new LatLng(22.254895,113.539458);




        final ShopLoader shopLoader = new ShopLoader();
        Handler handler=new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(@NonNull Message msg){
                drawShops(shopLoader.getShops());
                //super.handleMessage(msg);

            }
        };
        shopLoader.load(handler, "http://file.nidama.net/class/mobile_develop/data/bookstore.json");

        MapStatus.Builder builder=new MapStatus.Builder();
        builder.zoom(18.0f).target(centerPoint);
        mapView.getMap().setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));





        mapView.getMap().setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                Toast.makeText(getContext(), "此处的经纬度为"+centerPoint, Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        return view;
    }

    private void drawShops(ArrayList<Shop> shops) {
        for(int i=0;i<shops.size();i++){
            Shop shop=shops.get(i);
            //Log.i("test",""+shop.getDouble("latitude"));

            LatLng centerPoint = new LatLng(shop.getLatitude(),shop.getLongitude());
            MarkerOptions markerOptions=new MarkerOptions().icon(bitmap).position(centerPoint);

            Marker marker=(Marker)mapView.getMap().addOverlay(markerOptions);
            OverlayOptions textOption= new TextOptions().fontSize(30)
                    .fontColor(0xFFFF00FF).text(shop.getName()).position(centerPoint);
            mapView.getMap().addOverlay(textOption);
        }
    }

    class ShopLoader{
        private ArrayList<Shop> shops=new ArrayList<>();

        public ArrayList<Shop> getShops() {
            return shops;
        }
        public void load(final Handler handler, final String url) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String content = download(url);
                    parseJson(content);
                    handler.sendEmptyMessage(1000);
                }
            }).start();
        }

        public String download(String web){
            String test=null;
            try {
                //连接网络获取网络上的数据
                URL url=new URL(web);
                HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
                httpURLConnection.setUseCaches(false);
                httpURLConnection.connect();
                if(httpURLConnection.getResponseCode()==HttpURLConnection.HTTP_OK){
                    InputStream inputStream=httpURLConnection.getInputStream();
                    InputStreamReader inputStreamReader=new InputStreamReader(inputStream);
                    BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
                    //设置缓存
                    String line="";
                    StringBuffer stringBuffer=new StringBuffer();
                    while (null!=(line=bufferedReader.readLine())){
                        stringBuffer.append(line);
                    }

                    test= stringBuffer.toString();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return test;
        }
        public ArrayList<Shop> parseJson(String test){
            try {
                JSONObject jsonObject= new JSONObject(test);
                JSONArray jsonDatas= jsonObject.getJSONArray("shops");
                for (int i = 0; i < jsonDatas.length(); i++) {
                    JSONObject shopJson = jsonDatas.getJSONObject(i);
                    Shop shop = new Shop();
                    shop.setName(shopJson.getString("name"));
                    shop.setLatitude(shopJson.getDouble("latitude"));
                    shop.setLongitude(shopJson.getDouble("longitude"));
                    shop.setMemo(shopJson.getString("memo"));
                    shops.add(shop);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return shops;
        }
    }
    class Shop{
        private String name;
        private double latitude;
        private double longitude;
        private String memo;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public double getLatitude() {
            return latitude;
        }

        public void setLatitude(double latitude) {
            this.latitude = latitude;
        }

        public double getLongitude() {
            return longitude;
        }

        public void setLongitude(double longitude) {
            this.longitude = longitude;
        }

        public String getMeno() {
            return memo;
        }

        public void setMemo(String meno) {
            this.memo = meno;
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mapView.onResume();
    }
    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mapView.onPause();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mapView.onDestroy();
    }
}